package com.atguigu;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ThreadDemon5 {
	
	public static void main(String[] args) {
		
		final MyQueue myQueue = new MyQueue();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				myQueue.write();
			}
		}, "AA").start();
		
		for (int i = 0; i < 20; i++) {
			
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					myQueue.read();
				}
			}).start();
			
		}
		
		
		
	}

}


class MyQueue{
	
	private int i = 0;
	private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
	
	
	public void write(){
		readWriteLock.writeLock().lock();
		try {
			i = new Random().nextInt(50);
			System.out.println(Thread.currentThread().getName() + "-----" + i);
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			readWriteLock.writeLock().unlock();
		}
	}
	
	public void read(){
		readWriteLock.readLock().lock();
		try {
			System.out.println(Thread.currentThread().getName() + "-----" + i);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			readWriteLock.readLock().unlock();
		}
	}
	
	
	
	
}